<?php


namespace app\back\model;


use think\facade\Db;
use think\response\Json;
use \Exception;

class CompanyModel
{
    private static $_table = 'company'; // 公司表
    private static $_adminTable = 'admin'; // 管理员表
    private static $_roleTable = 'role'; // 司机表
    private static $_driverRouteTable = 'driver_route'; // 司机路线表
    private static $_orgTable = 'organization'; // 分拣中心表
    private static $_companyCenterTable = 'company_center'; // 公司-分拣中心中间表
    /**
     * @param $input
     * @param $info
     * @return Json
     */
    public static function list($input, $info)
    {
        try {
            $map = [
                ['c.admin_id', '=', $info['id']]
            ];
            if ($input['is_believe'] !== '') {
                $map[] = ['c.is_believe', '=', $input['is_believe']];
            }
            if ($input['name'] !== '') $map[] = ['c.name', 'like', "%{$input['name']}%"];
            $field = 'c.id,c.name as company_name,c.is_believe,c.driver_id,a.name as driver_name,r.name as role_name,c.create_time';
            $table = Db::table(self::$_table)->alias('c')
                ->leftJoin([self::$_adminTable => 'a'], 'a.id = c.driver_id')
                ->leftJoin([self::$_roleTable => 'r'], 'r.id = a.role_id')
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('c.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }

    /**授信公司
     * @param $input
     * @param $info
     * @return Json
     */
    public static function believe($input,$info)
    {
        try {
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['is_believe' => $input['is_believe']]);
            if ($rtn) return jsonSuccess('操作成功');
            return jsonFail('操作失败,请刷新页面重试');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
    /**获取有效的管理员列表
     * @param $info
     * @return Json
     */
    public static function getAdmin($info)
    {
        try {
            // 获取当前信息
            $map = [
                ['a.pid', '=', $info['id']],
                ['a.status', '=', 1],
                ['a.type', '=',4]
            ];
            $rtn = Db::table(self::$_adminTable)->alias('a')
                ->leftJoin([self::$_roleTable => 'r'], 'r.id = a.role_id')
                ->field('a.id,r.name as role_name,a.name')
                ->where($map)
                ->select()->toArray();
            if ($rtn) return jsonSuccess('获取成功',$rtn);
            return jsonFail('获取失败');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
    /**绑定司机
     * @param $input
     * @param $info
     * @return Json
     */
    public static function bindDriver($input, $info)
    {
        $flag = true;
        try {
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']]
            ];
            $table = self::$_adminTable;
            $sql = "select id from `{$table}` where id = {$input['driver_id']} and status = 1";
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->whereExists($sql)->update(['driver_id' => $input['driver_id']]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('绑定失败，刷新页面重试1');
            }
            // 添加路线
            $rtn = Db::table(self::$_driverRouteTable)->insert([
                'driver_id' => $input['driver_id'],
                'move_id' => $input['id'],
                'type' => 2
            ]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('绑定失败，刷新页面重试2');
            }
            Db::commit();
            return jsonSuccess('绑定成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**解绑司机
     * @param $input
     * @param $info
     * @return Json
     */
    public static function unbindDriver($input, $info)
    {
        $flag = true;
        try {
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['driver_id', '=', $input['driver_id']]
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update(['driver_id' => 0]);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('解绑失败，刷新页面重试');
            }
            // 删除司机路线
            $map = [
                ['move_id', '=', $input['id']],
                ['driver_id', '=', $input['driver_id']],
                ['type', '=', 2]
            ];
            $rtn = Db::table(self::$_driverRouteTable)->where($map)->delete();
            if ($rtn != 1) {
                Db::rollback();
                return jsonFail('解绑失败，刷新页面重试');
            }
            Db::commit();
            return jsonSuccess('解绑成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取有效分拣中心列表以及当前绑定的分拣中心
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getCenter($input,$info)
    {
        try {
            // 获取当前有效分拣中心
            $map = [
                ['admin_id', '=', $info['id']],
                ['status', '=', 1]
            ];
            $centerInfo = Db::table(self::$_orgTable)->field('id,name')->where($map)->select()->toArray();
            if (!$centerInfo) return jsonFail('没有可用的分拣中心');
            // 获取当前绑定的分拣中心
            $map = [
                ['cc.group_id', '=', $input['id']]
            ];
            $rtn = Db::table(self::$_companyCenterTable)->alias('cc')
                ->join([self::$_orgTable => 'o'], 'o.id = cc.center_id')
                ->field('cc.center_id')->where($map)->select()->toArray();
            $data['id'] = $input['id'];
            $data['center_ids'] = $rtn ? array_column($rtn, 'center_id') : [];
            return jsonSuccess('获取成功',['centerInfo' => $centerInfo, 'info' => $data]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑分拣中心
     * @param $input
     * @param $info
     * @return Json
     */
    public static function editCenter($input,$info)
    {
        $flag = false;
        try {
            $centerIds = explode(',', $input['center_ids']);
            $map = [
                ['admin_id', '=', $info['id']],
                ['id', 'in', $centerIds],
                ['status', '=', 1]
            ];
            $count = Db::table(self::$_orgTable)->where($map)->count();
            if ($count != count($centerIds)) return jsonFail('存在不可用的分拣中心，请重新编辑');
            Db::startTrans();
            $flag = true;
            // 删除原来的绑定
            Db::table(self::$_companyCenterTable)->where('group_id', $input['id'])->delete();
            // 添加新的绑定
            foreach ($centerIds as $centerId) {
                $insert[] = [
                    'group_id' => $input['id'],
                    'center_id' => $centerId
                ];
            }
            $rtn = Db::table(self::$_companyCenterTable)->insertAll($insert);
            if ($rtn !== count($centerIds)) {
                Db::rollback();
                return jsonFail('编辑失败,请刷新页面重试2');
            }
            Db::commit();
            return jsonSuccess('编辑成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
}